﻿using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Models;
using JiveMessenger.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace JiveMessenger.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class GetUserEmoticonsPage : BasicPage
    {
        private ObservableCollection<IContact> _users;
        public ObservableCollection<IContact> Users
        {
            get { return _users; }
            set
            {
                if (_users != value)
                {
                    _users = value;
                    RaisePropertyChanged("Users");
                }
            }
        }

        private IContact _selectedUser;
        public IContact SelectedUser
        {
            get { return _selectedUser; }
            set
            {
                if (_selectedUser != value)
                {
                    _selectedUser = value;
                    RaisePropertyChanged("SelectedUser");
                }
            }
        }


        public GetUserEmoticonsPage()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems != null)
            {
                ViewModelLocator locator = Application.Current.Resources["Locator"] as ViewModelLocator;
                IContact user = (IContact)e.AddedItems[0];

                this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                {
                    await Task.Delay(200);
                    this.GetUserEmoticonsControl.DataContext = new ViewModelGetUserEmoticons(locator.CurrentClient, user);
                });
            }

        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Tuple<bool, IContact> param = e.Parameter as Tuple<bool, IContact>;

            if (param == null || (bool)param.Item1 == false)
            {
                await StatusBar.GetForCurrentView().HideAsync();
                await Task.Delay(800);
                Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
                sb.Begin();
            }
            else
            {
                this.TextBoxPageHeader.Opacity = 1;
            }
            base.OnNavigatedTo(e);
            this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                Messenger.Default.Send(new NotificationMessageAction<IEnumerable<IContact>>(this, ViewModelContactList.MessengerCommands.GetContacts.ToString(), contacts =>
                {
                    this.Users = new ObservableCollection<IContact>(contacts.Where(x=>x.CustomEmoticons.Count>0));
                }));
                if (this.Users != null)
                {
                    await Task.Delay(100);
                    if (param == null || param.Item2 == null)
                        this.SelectedUser = this.Users.FirstOrDefault();
                    else
                    {
                        this.SelectedUser = param.Item2;
                    }
                }
            });
        }
        private void BasicPage_Loaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated += Current_Activated;
        }

        private void BasicPage_Unloaded(object sender, RoutedEventArgs e)
        {
            Window.Current.Activated -= Current_Activated;
        }

        async void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
                this.TextBoxPageHeader.Opacity = 0;
            else
            {
                await StatusBar.GetForCurrentView().HideAsync();
                await Task.Delay(800);
                Storyboard sb = this.Resources["ShowPageHeaderAnim"] as Storyboard;
                sb.Begin();
            }
        }

        private void GetUserEmoticonsControl_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if (args.NewValue != null && args.NewValue is ViewModelGetUserEmoticons)
            {
                this.AppBarButtonGetEmoticons.IsEnabled = true;
                this.AppBarButtonGetEmoticons.Command = ((ViewModelGetUserEmoticons)args.NewValue).AddEmoticonsCommand;

                this.AppBarButtonCheckAllItems.IsEnabled = true;
                this.AppBarButtonCheckAllItems.Command = ((ViewModelGetUserEmoticons)args.NewValue).CheckUncheckAllCommand;
                this.AppBarButtonCheckAllItems.CommandParameter = true;

                this.AppBarButtonUnCheckAllItems.IsEnabled = true;
                this.AppBarButtonUnCheckAllItems.Command = ((ViewModelGetUserEmoticons)args.NewValue).CheckUncheckAllCommand;
                this.AppBarButtonUnCheckAllItems.CommandParameter = false;

                var showProgressBinding = new Binding
                {
                    Path = new PropertyPath("ShowProgressOverlay"),
                     Mode= BindingMode.TwoWay,
                    Source = ((ViewModelGetUserEmoticons)args.NewValue)
                };
                var visibleProperty = CustomControls.ProgressOverlay.IsProgressOverlayVisibleProperty;
                this.ProgressOverlay.SetBinding(visibleProperty, showProgressBinding);

                var progressValueBinding = new Binding
                {
                    Path = new PropertyPath("ProgressValue"),
                    Mode = BindingMode.TwoWay,
                    Source = ((ViewModelGetUserEmoticons)args.NewValue)
                };
                var progressProperty = CustomControls.ProgressOverlay.ProgressValueProperty;
                this.ProgressOverlay.SetBinding(progressProperty, progressValueBinding);

            }
            else
            {
                this.AppBarButtonGetEmoticons.IsEnabled = false;
            }
        }
    }
}
